package commons.base.elasticsearch.jest;

import io.searchbox.client.JestClient;
import io.searchbox.client.JestClientFactory;
import io.searchbox.client.config.HttpClientConfig;
import io.searchbox.core.Bulk;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import io.searchbox.core.SearchResult.Hit;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import io.searchbox.indices.IndicesExists;

public class JestExample {

	public static void main(String[] args)throws Exception {
		JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig.Builder("http://localhost:9200")
                .multiThreaded(true)
                .build());
        JestClient client = factory.getObject();

        query(client);
	}
	
	public static void udpate(JestClient client)throws Exception{
		boolean indexExists = client.execute(new IndicesExists.Builder("k").build()).isSucceeded();
        if (indexExists) {
            client.execute(new DeleteIndex.Builder("jug").build());
        }
        client.execute(new CreateIndex.Builder("jug").build());
	}
	
	public static void query(JestClient client)throws Exception{
		String query = "{\n"
                + "    \"query\": {\n"
                + "        \"filtered\" : {\n"
                + "            \"query\" : {\n"
                + "                \"query_string\" : {\n"
                + "                    \"query\" : \"java\"\n"
                + "                }\n"
                + "            }"
                + "        }\n"
                + "    }\n"
                + "}";
        Search.Builder searchBuilder = new Search.Builder(query).addIndex("kamuy").addType("user");
        SearchResult result = client.execute(searchBuilder.build());
	}
	
	public static void bulk(JestClient client)throws Exception{
		Bulk.Builder bulkIndexBuilder = new Bulk.Builder();
//        for (Talk talk : talks) {
//            bulkIndexBuilder.addAction(new Index.Builder(talk).index("jug").type("talk").build());
//        }
//        client.execute(bulkIndexBuilder.build());
//        
//        List> hits = result.getHits(Talk.class);
//        for (Hit hit: hits) {
//            Talk talk = hit.source;
//            log.info(talk.getTitle());
//        }
	}

}
